/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.feature.h2sql;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import yhao.infra.feature.h2sql.mybatis.dialect.H2SqlDialect;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;

import static yhao.infra.feature.h2sql.ConfigFactory.*;

/**
 * H2SQL 配置类
 *
 * @author yoara
 */
@ComponentScan("yhao.infra.feature.h2sql.mybatis")
public class H2SqlConfig {
    @Autowired
    private Environment env;

    @Bean(name="h2sqlStatFilter")
    public FilterEventAdapter h2sqlStatFilter(){
        StatFilter statFilter = new StatFilter();
        statFilter.setMergeSql(true);
        statFilter.setSlowSqlMillis(5000);
        statFilter.setLogSlowSql(true);
        return statFilter;
    }

    @Bean(name="h2sqlCreateScheduler")
    public ScheduledExecutorFactoryBean h2sqlCreateScheduler(){
        ScheduledExecutorFactoryBean scheduledExecutorFactoryBean = new ScheduledExecutorFactoryBean();
        scheduledExecutorFactoryBean.setPoolSize(50);
        return scheduledExecutorFactoryBean;
    }

    @Bean(name="h2sqlDefaultDataSource",initMethod = "init",destroyMethod = "close")
    public DruidDataSource h2sqlDefaultDataSource(
            FilterEventAdapter h2sqlStatFilter,ScheduledExecutorService h2sqlCreateScheduler){
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName("org.h2.Driver");
        source.setUrl(env.getProperty(BASIC_H2SQL_URL));
        source.setUsername(env.getProperty(BASIC_H2SQL_USERNAME));
        source.setPassword(env.getProperty(BASIC_H2SQL_PASSWORD));
        source.setInitialSize(env.getProperty(BASIC_H2SQL_DRUID_INITIAL_SIZE,Integer.class,10));
        source.setMinIdle(env.getProperty(BASIC_H2SQL_DRUID_MIN_IDLE,Integer.class,10));
        source.setMaxActive(env.getProperty(BASIC_H2SQL_DRUID_MAX_ACTIVE,Integer.class,200));
        source.setMaxWait(env.getProperty(BASIC_H2SQL_DRUID_MAX_WAIT,Integer.class,30000));
        source.setTimeBetweenEvictionRunsMillis(
                env.getProperty(BASIC_H2SQL_DRUID_TIME_BETWEEN_EVICTION_RUNS_MILLIS,Integer.class,300000));
        source.setValidationQuery("select 'yhao'");
        source.setMinEvictableIdleTimeMillis(
                env.getProperty(BASIC_H2SQL_DRUID_MIN_EVICTABLE_IDLE_TIME_MILLIS,Integer.class,60000));
        source.setPoolPreparedStatements(false);

        List<Filter> filters = new ArrayList<>();
        filters.add(h2sqlStatFilter);
        source.setProxyFilters(filters);
        Properties properties = new Properties();
        properties.setProperty("druid.stat.sql.MaxSize",
                env.getProperty(BASIC_H2SQL_DRUID_STAT_SQL_MAX_SIZE,"3000"));

        source.setConnectProperties(properties);

        source.setCreateScheduler(h2sqlCreateScheduler);
        return source;
    }

    @Bean(name="h2sqlDataSource")
    public DruidDataSource h2sqlDataSource(DruidDataSource h2sqlDefaultDataSource){
        DruidDataSource defaultDataSource = h2sqlDefaultDataSource;
        //多库切换
        //DynamicDataSource source = new DynamicDataSource();
        //Map<Object, Object> targetDataSources =
        //        ImmutableMap.of("defaultDataSource",defaultDataSource);
        //source.setTargetDataSources(targetDataSources);
        //source.setDefaultTargetDataSource(defaultDataSource);

        return defaultDataSource;
    }

    @Bean(name="h2sqlSqlSessionFactory")
    public SqlSessionFactory h2sqlSqlSessionFactory(DruidDataSource h2sqlDataSource) throws Exception {
        SqlSessionFactory factory = ConfigFactory.
                makeSqlSessionFactory(env,h2sqlDataSource,H2SqlDialect.class);
        return factory;
    }

    @Bean(name="h2sqlJdbcTemplate")
    public JdbcTemplate h2sqlJdbcTemplate(DruidDataSource h2sqlDataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(h2sqlDataSource);
        return jdbcTemplate;
    }

    @Bean(name = "h2sqlTxManager")
    public PlatformTransactionManager h2sqlTxManager(DruidDataSource h2sqlDataSource) {
        return new DataSourceTransactionManager(h2sqlDataSource);
    }
}
